package cn.itcast.ssm.controller;

import cn.itcast.ssm.controller.validation.ValidGroup1;
import cn.itcast.ssm.vo.ItemsCustom;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Description:
 * Created by t410 on 2017/7/4.
 */
@Controller
@RequestMapping("/validate")
public class ValidationController {
    @RequestMapping("/edit")
    public String mapping(){
        return "validation/editItems";
    }

    // 商品信息修改提交
    // 在需要校验的pojo前边添加@Validated，在需要校验的pojo后边添加BindingResult
    // bindingResult接收校验出错信息
    // 注意：@Validated和BindingResult bindingResult是配对出现，并且形参顺序是固定的（一前一后）。
    // value={ValidGroup1.class}指定使用ValidGroup1分组的 校验
    // @ModelAttribute可以指定pojo回显到页面在request中的key
    @RequestMapping("/editItemsSubmit")
    public String editItemsSubmit(
            Model model,
            HttpServletRequest request,
            Integer id,
            @ModelAttribute("items") @Validated(value = { ValidGroup1.class }) ItemsCustom itemsCustom,
            BindingResult bindingResult
    ) throws Exception {
        System.out.println(itemsCustom);
        // 获取校验错误信息
        if (bindingResult.hasErrors()) {
            // 输出错误信息
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                // 输出错误信息
                System.out.println("getDefaultMessage = "+objectError.getDefaultMessage());
                System.out.println("getObjectName = "+objectError.getObjectName());
                System.out.println("getCode = "+objectError.getCode());

            }
            // 将错误信息传到页面
            model.addAttribute("allErrors", allErrors);
            //可以直接使用model将提交pojo回显到页面
            model.addAttribute("items", itemsCustom);


            RequestContext requestContext=new RequestContext(request);
            String keyAa=requestContext.getMessage("aa");
            System.out.println(keyAa);
            String keyAa1=requestContext.getMessage("items.name.length.error");
            System.out.println(keyAa1);
            model.addAttribute("name",requestContext.getMessage("items.name.length.error"));
            // 出错重新到商品修改页面
            return "validation/editItems";
        }

        model.addAttribute("v1","validation");
        return "success";
    }
}
